<?php

namespace App\Workerman;

use App\Models\Question;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class Helper
{


    public static function joinRoomCheck($groupSession, $uid)
    {
        $amIJoined = 0; //我是否已加入过
        $lockRoom = 0;
        $userData = 0;
        $userType = 0;
        if ($groupSession) {
            foreach ($groupSession as $session) {
                //$userData = isset($session['userData']) ? $session['userData'] : 0;
                if ($session['uid'] == $uid) {
                    $amIJoined = 1; //我已加入
                }
                if ($session['lock'] == 1) {
                    $lockRoom = 1; //房间锁定
                }
            }
            /*foreach ($userData as $key => $value) {
                if($value['uid'] == $uid){
                    $userType = $value;
                }
            }*/
            //var_dump($userType);

            if ($amIJoined === 0 && $lockRoom === 0) {
                return true;
            } else {
                return false;
            }
        }
        return true;
    }

    public static function joinRoomCheckv2($groupSession, $uid)
    {
        $amIJoined = 0; //我是否已加入过
        $lockRoom = 0;
        $userData = 0;
        $userType = 0;
        if ($groupSession) {
            foreach ($groupSession as $session) {
                if ($session['uid'] == $uid) {
                    $amIJoined = 1; //我已加入
                }
            }
            foreach ($groupSession as $session) {
                if (isset($session['userData'])) {
                    $userData = $session['userData'];
                    break;
                }
            }

            if ($amIJoined === 0) {
                if (! empty($userData) && $userData != 0) {
                    foreach ($userData as $key => $value) {
                        if ($value['uid'] == $uid) {
                            $userType = $value;
                        }
                    }
                    if (! empty($userType) && $userType != 0) {
                        return [true, $userType];
                    } else {
                        return [false, $groupSession];
                    }
                } else {
                    return [true, $userType];
                }
            } else {
                return [false, $groupSession];
            }
        }
        return [true, $userType];
    }

    /**
     * 获取题目
     *
     * @param int $number
     * @return array
     */
    public static function getQuestions($number = 5)
    {
        return Cache::store()->tags('pk_questions')->remember(rand(1, 100), 600, function () use ($number) {
            return Question::query()
                ->inRandomOrder()
                ->take($number)
                ->get()
                ->map(function (Question $question) {
                    $options = [];
                    foreach (range(1, 4) as $item) {
                        if ($desc = $question->getAttribute("option_$item")) {
                            $options[] = [
                                'id'      => $item,
                                'desc'    => $desc,
                                'isright' => $question->answer == $item ? 1 : 0,
                            ];
                        }
                    }
                    return [
                        'id'      => $question->id,
                        'title'   => $question->question,
                        'time'    => 15,    // 每题答题时间（秒）
                        'options' => $options,
                    ];
                })->toArray();
        });
    }

    /**
     * 随机返回一个机器人
     *
     * @return array
     */
    public static function getRobot()
    {
        // right：正确率（1 高 2 中 3 低）
        $robots = [
            [
                'id'    => 0,
                'name'  => '龚晓辉',
                'img'   => asset('h5/img/robot_1.png'),
                'right' => rand(1, 3),
            ],
            [
                'id'    => 0,
                'name'  => '婵娟',
                'img'   => asset('h5/img/robot_2.png'),
                'right' => rand(1, 3),
            ],
            [
                'id'    => 0,
                'name'  => '当当叮',
                'img'   => asset('h5/img/robot_3.png'),
                'right' => rand(1, 3),
            ],
            [
                'id'    => 0,
                'name'  => '袁秀秀',
                'img'   => asset('h5/img/robot_4.png'),
                'right' => rand(1, 3),
            ],
            [
                'id'    => 0,
                'name'  => '王同学',
                'img'   => asset('h5/img/robot_5.png'),
                'right' => rand(1, 3),
            ],
        ];

        return $robots[array_rand($robots)];
    }

    public static function robotId()
    {
        //机器人账号ID范围区间
        return rand(29261, 29310);
    }

    public static function robotHeader()
    {
        //机器人头像
        //return rand(29261,29310);
        return 'http://static.itv.cctv.com/yuedong/2018changcheng/image/pointer.png';
    }

    public static function robotAnswerData($question, $time = 15, $chance = 0.5)
    {
        $robotArr = [];
        $count = count($question);
        $count = $count <= 0 ? 1 : $count;
        $rightCount = ceil($count * $chance);
        $rightCount = $rightCount >= $count ? $count : $rightCount;
        $rightKeys = array_rand($question, $rightCount);
        $rightKeys = is_array($rightKeys) ? $rightKeys : array($rightKeys);

        foreach ($question as $key => $value) {
            $aTime = rand(1, $time - 1);
            if (in_array($key, $rightKeys)) {
                foreach ($value['options'] as $k => $v) {
                    if ($v['is_right'] == 1) {
                        $robotArr[$v['rid']]['answerId'] = $v['id'];
                        $robotArr[$v['rid']]['answerTime'] = $aTime;
                        break;
                    }
                }
            } else {
                foreach ($value['options'] as $k => $v) {
                    if ($v['is_right'] != 1) {
                        $robotArr[$v['rid']]['answerId'] = $v['id'];
                        $robotArr[$v['rid']]['answerTime'] = $aTime;
                        break;
                    }
                }
            }
        }

        return $robotArr;
    }

    /*public static function robotName(){
        $name_obj = new rndChinaName();
        $name = $name_obj->getName(2);
        return $name;
    }*/

    /*
    返回机器人随机答题信息(答案id和随机答题时间)
     */

    /**
     * 记录日志
     *
     * @param string $type
     * @param string $client_id
     * @param array $message
     */
    public static function log($type, $client_id = '', $message = [])
    {
        $log = [
            'time'         => date('[Y-m-d H:i:s]'),
            'REMOTE_ADDR'  => $_SERVER['REMOTE_ADDR'],
            'REMOTE_PORT'  => $_SERVER['REMOTE_PORT'],
            'GATEWAY_ADDR' => $_SERVER['GATEWAY_ADDR'],
            'GATEWAY_PORT' => $_SERVER['GATEWAY_PORT'],
            'client_id'    => $client_id,
            'message'      => $message,
        ];

        Log::info($type, $log);
    }
}
